﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ppt = Microsoft.Office.Interop.PowerPoint;

namespace ObjectModel.PowerPoint.New
{
    public class ResolvableTableTextRange : ResolvableTextRange
    {
        public ResolvableTableCellShape StoredShape { get; set; }

        public ResolvableTableTextRange() : base() // Parameterless constructor required for deserialization.
        { }

        // Constructor for use with table cell text ranges.
        public ResolvableTableTextRange(Ppt.TextRange textRange, Ppt.Table table, int row, int col) : base(textRange)
        {
            StoredShape = new ResolvableTableCellShape(table, row, col);
        }

        public override Ppt.Shape Shape
        {
            get { return StoredShape.Resolve() as Ppt.Shape; }
        }

        //public override object Resolve()
        //{
        //    Ppt.Shape shape = StoredShape.Resolve() as Ppt.Shape;
        //    return shape.TextFrame.TextRange.Characters(Start, Length);
        //}

        public override ResolvableShape GetParentShape()
        {
            return StoredShape.ParentShape;
        }

        public override bool Selected
        {
            get
            {
                Ppt.Selection sel = Globals.Application.ActiveWindow.Selection;

                if (sel.Type == Ppt.PpSelectionType.ppSelectionText)
                    if (StoredShape.Selected)
                        return TextRange.Start >= sel.TextRange.Start &&
                               TextRange.Start + TextRange.Length <= sel.TextRange.Start + sel.TextRange.Length;

                return false;
            }
        }

        public override bool ContainsSelection
        {
            get
            {
                return StoredShape.Selected && Contains(Globals.Application.ActiveWindow.Selection.TextRange);
            }
        }

        bool Contains(Ppt.TextRange textRangeToCompare)
        {
            // Note: this method assumes that it has already been verified that
            // the two text ranges being compared are from the same text frame.
            int start1 = textRangeToCompare.Start;
            int end1 = textRangeToCompare.Start + textRangeToCompare.Length;
            int start2 = TextRange.Start;
            int end2 = TextRange.Start + TextRange.Length;

            return start1 >= start2 && end1 <= end2;
        }
    }
}
